#include "ItemGenerator.h"

ItemGenerator::ItemGenerator(const std::string& entityModel, const std::string& entitySkin, const std::string& entity_type, const std::string& scale)
{
	node__ = smgr__->addEmptySceneNode(0);
	item_entinfo__["model"] = entityModel;
	item_entinfo__["skin"] = entitySkin;
	item_entinfo__["classname"] = entity_type;
	item_entinfo__["scale"] = scale;

	max_childs__ = 8;
	timeToSpawn__ = 15.0f;
	elapsedTime__ = 0.0f;
}

ItemGenerator::~ItemGenerator()
{
	std::vector<StaticEntity*>::iterator it = childs__.begin();
	while (it != childs__.end())
	{
		(*it)->setParent(0);
		it++;
	}
	// node__ erased in Entity::~Entity()
}

void ItemGenerator::setMaxChildren(unsigned int max_child)
{
	max_childs__ = max_child;
}

void ItemGenerator::setTimeToSpawn(float ttf)
{
	timeToSpawn__ = ttf;
}

void ItemGenerator::removeChild(StaticEntity* child)
{
	std::vector<StaticEntity*>::iterator it = childs__.begin();
	while (it != childs__.end())
	{
		if (*it == child)
		{
			childs__.erase(it);
			return;
		}
		it++;
	}
}

void ItemGenerator::update()
{
	if (childs__.size() >= max_childs__)
		return;
	
	elapsedTime__ += World::getWorld()->elapsedTime();

	if (elapsedTime__ > timeToSpawn__)
	{
		elapsedTime__ = 0.0f;
		std::map<std::string, std::string> spawn_map = item_entinfo__;

		float angle = World::getWorld()->randf() * 360.0f;
		vector3df p(32.0f, 0.0f, 0.0f);
		p.rotateXZBy(angle, vector3df(0.0f, 0.0f, 0.0f));
		p += getNode()->getPosition();
		{
			std::stringstream ss;
			ss << angle;
			spawn_map["angle"] = ss.str();
		}
		{
			std::stringstream ss;
			ss << p.X << ' ' << p.Z << ' ' << p.Y;
			spawn_map["origin"] = ss.str();
		}

		StaticEntity* e = World::getMap()->SpawnItem(spawn_map);
		e->setParent(this);
		childs__.push_back(e);
	}
}

